import {
	storage
} from './base.js'
import {
	BASE_URL
} from '@/config/app.config'
import {
	noTokenApiList,
	noLoadingApiList
} from '@/config/api.config.js'

// #ifdef APP-PLUS
var Fly = require('flyio/dist/npm/weex')
//#endif
// #ifdef H5
var Fly = require('flyio/dist/npm/fly')
//#endif
// #ifdef MP-WEIXIN
var Fly = require('flyio/dist/npm/wx')
//#endif
var fly = new Fly()

fly.config = {
	baseURL: BASE_URL,
	headers: {},
	//是否自动将Content-Type为“application/json”的响应数据转化为JSON对象
	parseJson: true,
	timeout: 60000
}

//添加请求拦截器
fly.interceptors.request.use((request) => {
	//打印出请求体
	// console.log('请求', request.url, request.body)

	const token = storage.get('token')
	if (token) {
		//给所有请求添加自定义header
		request.headers['Authorization'] = token
	} else {
		// 终止请求
		if (!noTokenApiList.includes(request.url)) {
			return Promise.reject()
		}
	}
	if (!noLoadingApiList.includes(request.url)) {
		uni.showLoading({
			mask: true,
			title: ''
		})
	}

	//可以显式返回request, 也可以不返回，没有返回值时拦截器中默认返回request
	return request
})

//添加响应拦截器，响应拦截器会在then/catch处理之前执行
fly.interceptors.response.use(
	(response) => {
		// console.log(response)
		if (!noLoadingApiList.includes(response.request.url)) {
			uni.hideLoading()
		}
		//只将请求结果的data字段返回
		if (!response) return
		switch (response.data.state) {
			case 1:
				return response.data
			case 2:
				uni.showToast({
					title: response.data.message,
					icon: 'none'
				})
				return response.data
				break
			case 3:
				uni.showToast({
					title: response.data.message,
					icon: 'none'
				})
				return response.data
				break
			case 4:
				uni.showToast({
					title: '没有权限',
					icon: 'none'
				})
				break
			case 5:
				// 登录过期
				uni.showToast({
					title: '登录过期',
					icon: 'none'
				})
				uni.navigateTo({
					url: '/pages/account/login/login'
				})
				break
		}
	},
	//发生网络错误后会走到这里
	(error) => {
		uni.hideLoading()
		if (!error.response) return
		switch (error.response.status) {
			case 401:
				uni.showToast({
					title: '无访问权限',
					icon: 'none'
				})
				break
			case 500: // 服务器出小差了，请稍后再试
				uni.showToast({
					title: '服务器出小差了，请稍后再试',
					icon: 'none'
				})
				break
			default:
				uni.showToast({
					title: '服务器出小差了，请稍后再试',
					icon: 'none'
				})
				break
		}
		return Promise.reject(error)
	}
)

export default fly
